﻿/*****************************************************************
// Copyright (C) 2011-2099 ZdSoft Corporation
// All rights reserved.
// 
// Author:       wunaigong
// Create Date:  2011-07-20 22:15:47
// Usage: Xml操作类
//
// RevisionHistory
// Date				Author				Description
*****************************************************************/

using System;
using System.IO;
using System.Xml;
using System.Xml.Serialization;

namespace Portal
{
    public class XmlUtils
    {
        public static object Deserialize(Type currentType, Stream objStream)
        {
            var objObject = new XmlSerializer(currentType).Deserialize(objStream);
            objStream.Close();
            return objObject;
        }

        public static object Deserialize(Type currentType, string filePath)
        {
            object objObject;
            var objSerializer = new XmlSerializer(currentType);
            try
            {
                var fileStream = File.Open(filePath, FileMode.Open, FileAccess.Read);
                objObject = objSerializer.Deserialize(fileStream);
                fileStream.Close();
            }
            catch (Exception)
            {
                objObject = null;
            }
            return objObject;
        }

        public static string Serialize(object obj)
        {
            var xmlDoc = new XmlDocument();
            var xser = new XmlSerializer(obj.GetType());
            var sw = new StringWriter();
            xser.Serialize(sw, obj);
            xmlDoc.LoadXml(sw.GetStringBuilder().ToString());
            var xmlDocEl = xmlDoc.DocumentElement;
            if (xmlDocEl != null)
            {
                xmlDocEl.Attributes.RemoveNamedItem("xmlns:xsd");
                xmlDocEl.Attributes.RemoveNamedItem("xmlns:xsi");
                return xmlDocEl.OuterXml;
            }
            return null;
        }

        public static void Serialize(object obj, string filePath)
        {
            var fs = new FileStream(filePath, FileMode.Create);
            new XmlSerializer(obj.GetType()).Serialize(fs, obj);
            fs.Close();
        }
    }
}